<!doctype html>
<html lang="en-US">
  <head>
    <link href="/assets/index.css" rel="stylesheet" type="text/css" />
    <script type="importmap">
      {
        "imports": {
          "@testduet/wait-for": "https://esm.sh/@testduet/wait-for",
          "jest-mock": "https://esm.sh/jest-mock",
          "react": "https://esm.sh/react@18.3.1",
          "react-dom": "https://esm.sh/react-dom@18.3.1",
          "react-dom/": "https://esm.sh/react-dom@18.3.1/"
        }
      }
    </script>
    <script type="module">
      import React from 'react';

      window.React = React;
    </script>
    <script defer crossorigin="anonymous" src="/test-harness.js"></script>
    <script defer crossorigin="anonymous" src="/test-page-object.js"></script>
    <script defer crossorigin="anonymous" src="/__dist__/webchat-es5.js"></script>
  </head>
  <body>
    <main id="webchat"></main>
    <script defer type="module">
      import { spyOn } from 'jest-mock';
      import { waitFor } from '@testduet/wait-for';
      import React, { createElement, memo } from 'react';
      import { createRoot } from 'react-dom/client';

      run(async function () {
        const {
          testHelpers: { createDirectLineEmulator },
          WebChat: {
            Components: { Composer },
            hooks: { useActivities, useBuildRenderActivityCallback },
            middleware: { activityComponent, createActivityPolymiddleware, createActivityPolymiddlewareFromLegacy },
            ReactWebChat
          }
        } = window;

        const { directLine, store } = createDirectLineEmulator();

        const rootElement = document.getElementsByTagName('main')[0];

        const polymiddleware = [
          createActivityPolymiddlewareFromLegacy(
            () => next => request => {
              const child = next({
                activity: {
                  ...request.activity,
                  text: request.activity.text.toUpperCase()
                }
              });

              return () =>
                createElement(
                  'div',
                  {},
                  createElement('div', {}, `<Upstream data-activity-text="${request.activity.text}">`),
                  child(),
                  createElement('div', {}, '</Upstream>')
                );
            },
            () => next => request => {
              return () =>
                createElement(
                  'div',
                  {},
                  createElement('div', {}, `<Downstream data-activity-text="${request.activity.text}" />`)
                );
            }
          )
        ];

        // WHEN: Web Chat is being rendered.
        createRoot(rootElement).render(
          createElement(ReactWebChat, {
            directLine,
            polymiddleware,
            store
          })
        );

        await pageConditions.uiConnected();

        spyOn(console, 'warn');

        // WHEN: A message arrive: "Hello, World!"
        await directLine.emulateIncomingActivity({
          text: 'Hello, World!',
          timestamp: 0,
          type: 'message'
        });

        // THEN: Should render both legacy middleware and polymiddleware.
        await waitFor(() =>
          expect(rootElement?.querySelector('.webchat__basic-transcript__transcript')?.children).toHaveLength(1)
        );

        // THEN: Downstream should show original request.
        const activity = rootElement?.querySelector('.webchat__basic-transcript__activity-body');

        expect(activity).toHaveProperty(
          'textContent',
          '<Upstream data-activity-text="Hello, World!"><Downstream data-activity-text="HELLO, WORLD!" /></Upstream>'
        );

        // THEN: Should not warn because request change is allowed in legacy activity middleware.
        await expect(console.warn).toHaveBeenCalledTimes(0);

        // THEN: Should match snapshot.
        await host.snapshot('local');
      });
    </script>
  </body>
</html>
